<template>
  <img :src="imageUrl" />
</template>

<script setup lang="ts">
import ColorThief from 'colorthief';

const emit = defineEmits<{
  'imgLoad:thiefColor': [value: string[]];
}>();

// ColorThief可以解析图片的主要颜色
const colorThief = new ColorThief();

const props = defineProps({
  imageUrl: {
    type: String, // 图片地址
    required: true,
  },
  colorQuantity: {
    type: Number, // 颜色数量
    default: 3,
  },
});

// 获取图片主要颜色
const getThiefColor = async (img: HTMLImageElement) => {
  const colors = await colorThief.getPalette(img, props.colorQuantity);
  return colors.map((color) => {
    return `rgb(${color[0]}, ${color[1]}, ${color[2]})`;
  });
};

// 图片加载完成后获取颜色
const handleImgLoad = async () => {
  const img = new Image();
  img.src = props.imageUrl;
  img.crossOrigin = '';
  img.onload = async () => {
    const colors = await getThiefColor(img);
    emit('imgLoad:thiefColor', colors);
  };
};

watch(
  () => props.imageUrl,
  () => {
    handleImgLoad();
  },
  { immediate: true },
);
</script>

<style scoped lang="scss"></style>
